package com.zjh.photoshopstudy.app.video;


import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.lzy.okgo.model.Progress;
import com.zjh.photoshopstudy.Model.AppUserEntity;
import com.zjh.photoshopstudy.Model.VideoEntity;
import com.zjh.photoshopstudy.R;
import com.zjh.photoshopstudy.Utils.CommentImageClick;
import com.zjh.photoshopstudy.Utils.Data;
import com.zjh.photoshopstudy.Utils.LinkClick;
import com.zjh.photoshopstudy.app.main.MainListAdapter;
import com.zjh.photoshopstudy.app.main.OnGetVideoListener;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class VideoInfoFragment extends Fragment implements OnGetVideoListener {
    private VideoEntity mVideoEntity;
    private boolean isCollection = false;
    private boolean isLogin = false;
    private Button collectBtn;
    private Button videoDownloadBtn;
    private Button materiaDownloadBtn;
    private int videoDownloadState = 0;
    private int materiaDownloadState = 0;
    TextView time;
    RecyclerView recyclerView;

    public void setVideoDownloadState(int videoDownloadState) {
        this.videoDownloadState = videoDownloadState;
    }

    public void setMateriaDownloadState(int materiaDownloadState) {
        this.materiaDownloadState = materiaDownloadState;
    }

    public void setCollection(boolean collection) {
        isCollection = collection;
    }

    public void setLogin(boolean login) {
        isLogin = login;
    }

    public VideoInfoFragment() {
        // Required empty public constructor
    }

    public void onCollectionSuccess() {
        isCollection = true;
        collectBtn.setText("已收藏");
    }

    public void onCancelCollectionSuccess() {
        isCollection = false;
        collectBtn.setText("收藏");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_video_info, container, false);
        TextView title = view.findViewById(R.id.title);
        TextView type = view.findViewById(R.id.type);
        TextView level = view.findViewById(R.id.level);
        TextView date = view.findViewById(R.id.date);
        time = view.findViewById(R.id.time);
        TextView name = view.findViewById(R.id.name);
        TextView resume = view.findViewById(R.id.resume);
        ImageView uicon = view.findViewById(R.id.uicon);
        recyclerView = view.findViewById(R.id.videoList);
        collectBtn = view.findViewById(R.id.collectBtn);
        videoDownloadBtn = view.findViewById(R.id.videoDownloadBtn);
        materiaDownloadBtn = view.findViewById(R.id.materiaDownloadBtn);
        if (isCollection) {
            collectBtn.setText("已收藏");
        }
        updateBtn(videoDownloadState, materiaDownloadState);
        mVideoEntity = (VideoEntity) getArguments().getSerializable("videoEntity");
        title.setText(mVideoEntity.getvTitle());
        type.setText(Data.TYPES[mVideoEntity.getvType()]);
        level.setText(Data.LEVELS[2]);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        date.setText(dateFormat.format(mVideoEntity.getvUpdateTime()));
        AppUserEntity appUserEntity = mVideoEntity.getvAppUserEntity();
        name.setText(appUserEntity.getuName());
        resume.setMovementMethod(LinkMovementMethod.getInstance());
        resume.setText(getSpannableString(mVideoEntity.getvContent()));
        Glide.with(getContext()).load(Data.webRoot_URL + appUserEntity.getuIcon()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(uicon);
        VideoHttp videoHttp = new VideoHttp();
        Map<String, Object> map = new HashMap<>();
        map.put("vType", mVideoEntity.getvType());
        videoHttp.getVideoList(this, map);
        return view;
    }

    void updateBtn(int videoState, int materiaState) {
        videoDownloadState = videoState;
        materiaDownloadState = materiaState;
        if (videoDownloadState == Progress.LOADING) {
            videoDownloadBtn.setText("视频下载中");
        } else if (videoDownloadState == Progress.FINISH) {
            videoDownloadBtn.setText("视频已下载");
        } else if (videoDownloadState == Progress.NONE) {
            videoDownloadBtn.setText("视频下载");
        }
        if (materiaDownloadState == Progress.LOADING) {
            materiaDownloadBtn.setText("素材下载中");
        } else if (materiaDownloadState == Progress.FINISH) {
            materiaDownloadBtn.setText("素材已下载");
        } else if (materiaDownloadState == Progress.NONE) {
            materiaDownloadBtn.setText("素材下载");
        }
    }

    private SpannableStringBuilder getSpannableString(String text) {
        String s = "<link>";
        String e = "</link>";
        String s2 = "<i>";
        String e2 = "</i>";
        List<String> linkList = new ArrayList<>();
        List<String> imageList = new ArrayList<>();
        while (text.contains(s) && text.contains(e)) {
            String item = text.substring(text.indexOf(s), text.indexOf(e) + 7);
            String url = item.substring(item.indexOf(">") + 1, item.lastIndexOf("<"));
            linkList.add(url);
            text = text.replaceFirst(item, "打开链接 ");
        }
        while (text.contains(s2) && text.contains(e2)) {
            String item = text.substring(text.indexOf(s2), text.indexOf(e2) + 4);
            String url = item.substring(item.indexOf(">") + 1, item.lastIndexOf("<"));
            imageList.add(url);
            text = text.replaceFirst(item, "查看图片 ");
        }
        SpannableStringBuilder spannable = new SpannableStringBuilder(text);
        addSpanable(text, "查看图片 ", spannable, imageList);
        addSpanable(text, "打开链接 ", spannable, linkList);

        return spannable;
    }

    private void addSpanable(String temp, String s, SpannableStringBuilder spannable, List<String> list) {
        int current = 0;
        int index = 0;
        while (temp.contains(s)) {
            int i = temp.indexOf(s);
            int start = i + current;
            int end = start + s.length();
            if (s.equals("查看图片 ")) {
                CommentImageClick clickableSpan = new CommentImageClick(getContext(), "upload/image/" + list.get(index));
                spannable.setSpan(clickableSpan, start, end - 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            } else {
                LinkClick clickableSpan = new LinkClick(getContext(), list.get(index));
                spannable.setSpan(clickableSpan, start, end - 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            }
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#FF00B8D4"));
            spannable.setSpan(colorSpan, start, end - 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            current = end;
            temp = temp.substring(i + s.length());
            index++;
        }
    }

    @Override
    public void getVideoListSuccess(List<VideoEntity> list) {
        MainListAdapter adapter = new MainListAdapter(list, getContext());
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
    }

    public void setTime(long duration) {
        time.setText("时长 " + duration / 60 + ":" + duration % 60);
    }
}
